package com.xxyuan.batch._14_job_start_test;

import com.xxyuan.batch._01_hello.HelloJob;
import org.junit.jupiter.api.Test;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(classes = App.class)
public class StartJobTest {
    /**
     * job调度器
     */
    @Autowired
    private JobLauncher jobLauncher;

    /***
     * job构造器工厂
     */
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    /**
     * step构造器工厂
     */
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    public Tasklet tasklet() {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                //要执行的逻辑-step1步骤执行逻辑
                System.out.println("================================================================");
                System.out.println("hello spring batch!");
                System.out.println("================================================================");
                return RepeatStatus.FINISHED;
            }
        };
    }

    public Step step1() {
        //tasklet step 执行逻辑，类似 Thread()--->可以执行runable接口
        return stepBuilderFactory.get("step1").tasklet(tasklet())
                .build();
    }

    public Job job() {
        return jobBuilderFactory.get("start-test-job").start(step1()).build();
    }

    @Test
    public void testStart() throws Exception {
        jobLauncher.run(job(),new JobParameters());
    }
}
